package main

import (
	"fmt"

	"github.com/hyperledger/fabric/core/chaincode/shim"
	pb "github.com/hyperledger/fabric/protos/peer"
)

type Object struct {
	ID   string `json:"ID"`
	Hash string `json:"hash"`
}

func (t *Object) Init(stub shim.ChaincodeStubInterface) pb.Response {
	objects := []Object{
		{ID: "object_0", Hash: "ec13a4c02aaa0ef53893742d5bf7d14c960333e0275a9c6472774e85c9f502c5"},
	}

	for _, object := range objects {
		err := stub.PutState(object.ID, []byte(object.Hash))
		if err != nil {
			return shim.Error("Failed to init.")
		}
	}
	return shim.Success(nil)
}

func (t *Object) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
	function, args := stub.GetFunctionAndParameters()
	if function == "create" { // create object
		return t.create(stub, args)
	} else if function == "delete" { // delete object
		return t.delete(stub, args)
	} else if function == "read" { // read object
		return t.read(stub, args)
	}
	return shim.Error("Invalid invoke function name. Expecting \"creat\" \"delete\" \"read\"")
}

// Create new object with its hash
func (t *Object) create(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	err := stub.PutState(args[0], []byte(args[1]))
	if err != nil {
		return shim.Error("Failed to put state")
	}
	return shim.Success(nil)
}

// Deletes object from state
func (t *Object) delete(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	if len(args) != 1 {
		return shim.Error("Incorrect number of arguments. Expecting 1")
	}
	// Delete the key from the state in ledger
	err := stub.DelState(args[0])
	if err != nil {
		return shim.Error("Failed to delete state")
	}
	return shim.Success(nil)
}

// query an object hash with given object ID
func (t *Object) read(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	// Get the state from the ledger
	Avalbytes, err := stub.GetState(args[0])
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get state for " + args[0] + "\"}"
		return shim.Error(jsonResp)
	}
	return shim.Success(Avalbytes)
}

func main() {
	err := shim.Start(new(Object))
	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}
